﻿using System;
using System.Web.Mvc;

namespace Solution.Provide.Mvc
{
    /// <summary>
    /// ASP.NET MVC controller 基类，包含异常处理
    /// </summary>
    [RequireAuthorize]
    [LogErrorException]
    public abstract class BaseWebController : Controller
    {
        #region 字段

        private Type _actionReturnType;

        #endregion 字段

        #region 公共方法

        public StandardJsonResult Try(Action action)
        {
            var result = new StandardJsonResult();
            result.Try(action);
            return result;
        }

        public StandardJsonResult<T> Try<T>(Func<T> action)
        {
            var result = new StandardJsonResult<T>();
            result.Try(() =>
            {
                result.Value = action();
            });
            return result;
        }

        #endregion 公共方法

        #region 保护方法

        // protected abstract string AreaName { get; }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var action = filterContext.ActionDescriptor as ReflectedActionDescriptor;
            if (action != null)
            {
                _actionReturnType = action.MethodInfo.ReturnType;
            }
            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {
            Logger.Error("system", filterContext.Exception);

            if (_actionReturnType == null)
            {
                base.OnException(filterContext);
                return;
            }
            string error;
            if (filterContext.Exception is ShowException)
            {
                error = filterContext.Exception.Message;
            }
            else
            {
                error = ExceptionExtension.GetAllMessages(filterContext.Exception);
            }
            if (_actionReturnType == typeof(StandardJsonResult) || (_actionReturnType == typeof(StandardJsonResult<>)))
            {
                var result = new StandardJsonResult();
                result.Fail(error);
                filterContext.Result = result;
            }
            else if (_actionReturnType == typeof(PartialViewResult))
            {
                filterContext.Result = new ContentResult() { Content = error };
            }
            else
            {
                //如果是ajax则返回一个json的结果
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var result = new StandardJsonResult();
                    result.Fail(error);
                    filterContext.Result = result;
                }
                else
                {
                    filterContext.Result = Error(error);
                }


            }
            filterContext.ExceptionHandled = true;
        }

        /// <summary>
        /// 普通消息提醒页面
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected virtual ActionResult Message(string message)
        {
            var model = new LayoutViewModel<string>();
            model.Model = message;
            return View("~/views/shared/message.cshtml", model);
        }

        //protected ViewResult AreaView(string path, object model = null)
        //{
        //    return View("~/areas/" + AreaName + "/views/" + path, model);
        //}
        //protected PartialViewResult AreaPartialView(string path, object model = null)
        //{
        //    return PartialView("~/areas/" + AreaName + "/views/" + path, model);
        //}
        /// <summary>
        /// 错误页面
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected ActionResult Error(string message)
        {
            var model = new LayoutViewModel();
            model.Error = message;
            return View("~/views/shared/_Error.cshtml", model);
        }

        /// <summary>
        /// 当前登录用的ID
        /// </summary>
        /// <returns></returns>
        protected Guid GetUserId()
        {
            return Guid.Parse(FormTicketHelper.GetUserId());
        }

        #endregion 保护方法
    }
}